package com.ma.webSocket;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.tomcat.util.net.SendfileState;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ConcurrentModificationException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ProjectName: project
 * @Package: com.ma.webSocket
 * @ClassName: AddTeamSocket
 * @Author: YHHHH
 * @Description: 加入小组时发送的审核消息
 * @Date: 2021/3/12 18:45
 * @Version: 1.0
 */
@Slf4j
@Component
@ServerEndpoint("/TeamSocket/{number}/{toNumber}")
public class AddTeamSocket {

    private Session session; //给客户端发送消息

    private String number;    //客户端用户名

    private String toNumber;    //发送到另一个客户端的名字

    private static ConcurrentHashMap<String ,AddTeamSocket> webSocket = new ConcurrentHashMap<>();


    @OnOpen
    public void OnOpen(Session session, @PathParam("number")String number,@PathParam("toNumber")String toNumber){
        this.session = session;
        this.number = number;
        this.toNumber = toNumber;
        webSocket.put(number,this);
        webSocket.put(toNumber,this);
        System.out.println("发送者"+number);
        System.out.println("接受者"+toNumber);
        log.info(("连接成功！"));
    }

    @OnClose
    public void  OnClose(){
        webSocket.remove(this.number);
        log.info("退出成功！");
    }


    @OnMessage
    public void OnMessage(String number){
        number=this.number;
        String backMessage= "接到来自"+ number+"的入队请求，请及时查看！";
        //接受到消息后返回给队长
        Sending(toNumber,backMessage);



    }


    //发送消息
    public  void  Sending(String toNumber,String message){
        try {
            webSocket.get(toNumber).session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
